package com.grass.finding.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grass.finding.model.domain.Comments;
import com.grass.finding.service.CommentsService;
import com.grass.finding.mapper.CommentsMapper;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author 20158
* @description 针对表【comments(帖子评论)】的数据库操作Service实现
* @createDate 2023-04-25 18:51:48
*/
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments>
    implements CommentsService{

    @Autowired
    CommentsMapper commentsMapper;

    @Override
    public List<List<Comments>> getCommetsByLost(Integer lostId) {
        List<Comments> list = commentsMapper.getCommetsByLost(lostId);
        List<List<Comments>> lists = parseListComments(list);

        return lists;
    }

    private List<List<Comments>> parseListComments(List<Comments> list){
        List<List<Comments>> res = new ArrayList<>();
        int cnt = 0;
        /**
         * commentId 和 数组下标的hash
         */
        Map<Integer, Integer> posMap = new HashMap<>();
        /**
         * commentId 和 用户名的hash
         */
        Map<Integer, String> usernameMap = new HashMap<>();

        for (Comments comments : list) {
            if (comments.getParentId() == 0) {
                posMap.put(comments.getCommentId(), cnt++);
                comments.setIndex(cnt-1);
                res.add(new ArrayList<>(Arrays.asList(comments)));
            }
            usernameMap.put(comments.getCommentId(), comments.getUserName());
        }
        for(Comments comments : list){
            if(comments.getParentId() == 0) continue;
            if(comments.getReplyId() != 0){
                comments.setReplyUsername(usernameMap.get(comments.getReplyId()));
            }
            comments.setIndex(posMap.get(comments.getParentId()));
            res.get(posMap.get(comments.getParentId())).add(comments);
        }
//        System.out.println(res);
        return res;
    }

}




